package com.caine.disr.config;

import com.caine.disr.entity.RingEvent;
import com.caine.disr.handler.RingEventHandler;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

@Configuration
public class DisruptorConfig {

    private int coreThread = 5;

    @Bean
    public RingBuffer createRingBuffer() {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        Disruptor disruptor = new Disruptor(() -> new RingEvent(), 1024 * 1024, threadFactory, ProducerType.MULTI, new BusySpinWaitStrategy());
        List<RingEventHandler> list = new ArrayList<>();
        for (int i = 0; i < coreThread; i++) {
            list.add(new RingEventHandler());
        }
        disruptor.handleEventsWithWorkerPool(list.toArray(new RingEventHandler[list.size()]));
        RingBuffer ringBuffer = disruptor.start();
        return ringBuffer;
    }
}
